package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> data) {
        if (data != null && data.size() > 0) {
            //循环得到每一个OrderSetting
            for (OrderSetting orderSetting : data) {
                //判断当前日期是否进行了预约设置
                long countByyOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                if (countByyOrderDate > 0) {
                    //已经设置过了,修改可预约人数
                    orderSettingDao.editNumberByOrderDate(orderSetting);
                } else {
                    //还没有设置过,进行添加数据
                    orderSettingDao.add(orderSetting);
                }
            }
        }
    }

    @Override
    public List<Map> getOrdersettingByMonth(String date) { //yyyy-MM
        String begin = date + "-1";
        String end = date + "-31";

        Map<String, String> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        List<OrderSetting> list = orderSettingDao.getOrdersettingByMonth(map);

        List<Map> result = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (OrderSetting orderSetting : list) {
                Map<String, Object> m = new HashMap<>();
                m.put("date", orderSetting.getOrderDate().getDate());
                m.put("number", orderSetting.getNumber());
                m.put("reservations", orderSetting.getReservations());
                result.add(m);
            }
        }
        return result;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        long countByyOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if (countByyOrderDate>0){
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }else {
            orderSettingDao.add(orderSetting);
        }
    }
}
